package com.wstuo.common.config.onlinelog.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;


import com.opensymphony.xwork2.ActionSupport;
import com.wstuo.common.config.onlinelog.dto.LogDTO;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.TimeUtils;
import com.wstuo.common.util.ZipUtils;

@SuppressWarnings("serial")
public class LogAction extends ActionSupport{
	private static final Logger LOGGER = Logger.getLogger(LogAction.class);
	private int page = 1;
	private int rows = 10;
	private PageDTO pageDTO;
	private String fileName;
	private InputStream inputStream;
	private Date startTime;
	private Date endTime;
	private String zipType;
	
	private final String ZIPTYPE_ONLINELOG = "onlineLog";
	//private final String ZIPTYPE_ERRORLOG = "errorLog";
	private final String ZIPTYPE_OPTLOG = "optLog";
	private final String ONLINELOGPATH=AppConfigUtils.getInstance().getOnlineLogPath();//在线日志
	private final String OPTLOGPATH=AppConfigUtils.getInstance().getOptLogPath();  //操作日志
	private final String ERRLOGPATH=AppConfigUtils.getInstance().getErrLogPath();  //错误日志
	private final String MULTIZIPDIRPATH=AppConfigUtils.getInstance().getMultiZipDirPath();//批量下载
	

	public String getZipType() {
		return zipType;
	}

	public void setZipType(String zipType) {
		this.zipType = zipType;
	}

	public Date getStartTime() {
		return startTime;
	}

	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public PageDTO getPageDTO() {
		return pageDTO;
	}

	public void setPageDTO(PageDTO pageDTO) {
		this.pageDTO = pageDTO;
	}

	/**
	 * 用户在线日志分页列表
	 * @return
	 */
	public String userOnlinePage(){
		List<LogDTO> dtos = getFileDTO(ONLINELOGPATH);
		getLogPageDTO(dtos);
		return "logPageDTO";
	}
	
	/**
	 * 用户操作日志分页列表
	 * @return
	 */
	public String userOptPage(){
		List<LogDTO> dtos = getFileDTO(OPTLOGPATH);
		getLogPageDTO(dtos);
		return "logPageDTO";
	}
	
	/**
	 * 错误日志分页列表
	 * @return
	 */
	public String errLogPage(){
		List<LogDTO> dtos = getFileDTO(ERRLOGPATH);
		getLogPageDTO(dtos);
		return "logPageDTO";
	}


	/**
	 * 下载用户在线日志
	 * @return
	 */
	public String downloadOnlineLog(){
		try {
			inputStream = new FileInputStream(ONLINELOGPATH+"/"+fileName);
		} catch (FileNotFoundException e) {
			LOGGER.error(e);
		}
		return "download";
	}
	
	/**
	 * 下载操作日志文件
	 * @return
	 */
	public String downloadOptLog(){
		try {
			inputStream = new FileInputStream(OPTLOGPATH+"/"+fileName);
		} catch (FileNotFoundException e) {
			LOGGER.error(e);
		}
		return "download";
	}
	
	/**
	 * 下载错误日志文件
	 * @return
	 */
	public String downloadErrLog(){
		try {
			inputStream = new FileInputStream(ERRLOGPATH+"/"+fileName);
		} catch (FileNotFoundException e) {
			LOGGER.error(e);
		}
		return "download";
	}
	
	/**
	 * 批量压缩
	 * @return
	 */
	public String multiZip(){
		String path = null;
		if(ZIPTYPE_ONLINELOG.equals(zipType)){
			path = ONLINELOGPATH;
		}else if(ZIPTYPE_OPTLOG.equals(zipType)){
			path = OPTLOGPATH;
		}else{
			path = ERRLOGPATH;
		}
		if(null != path){
			fileName = "ZIPFile"+new Date()+ZipUtils.EXTENSION_ZIP;
			fileName = fileName.replace(" ", "_").replace(":", "_");
			fileMkdirs(MULTIZIPDIRPATH);
			String desFile = MULTIZIPDIRPATH+"/"+fileName;
			File file = new File(path);
			try {
				ZipUtils.zip(file, desFile, startTime, endTime);
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
		return "multilZip";
	}
	
	/**
	 * 批量压缩文件下载
	 * @return
	 */
	public String downloadMultiZip(){
		fileMkdirs(MULTIZIPDIRPATH);
		String file = MULTIZIPDIRPATH+"/"+fileName;
		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			LOGGER.error(e);
		}
		return "downloadZip";
	}
	/**
	 * 删除批量压缩文件
	 */
	public void deleteNultiZip(){
		String path = MULTIZIPDIRPATH+"/"+fileName;
		new File(path).deleteOnExit();
	}
	/**
	 * 获取日志的分页信息
	 * @param dtos
	 */
	private void getLogPageDTO(List<LogDTO> dtos) {
		List<LogDTO> logDTOList = new ArrayList<LogDTO>();
		int start = (page - 1) * rows;
		for(int i = dtos.size() - start - 1; i >= 0 ; i --){
			if(i < dtos.size()){
				logDTOList.add(dtos.get(i));
			}
		}
		setPageDTOInfo(logDTOList, start, dtos);
	}
	/**
	 * 设置文件分页
	 * @param logDTOList
	 * @param start
	 * @param dtos
	 */
	private void setPageDTOInfo(List<LogDTO> logDTOList, int start,
			List<LogDTO> dtos) {
		pageDTO = new PageDTO();
		pageDTO.setData(logDTOList);
		pageDTO.setPage(page);
		pageDTO.setPageCount((int)Math.ceil(((float)dtos.size())/rows));
		pageDTO.setRows(rows);
		pageDTO.setStart(start);
		pageDTO.setTotal(logDTOList.size());
		pageDTO.setTotalSize(dtos.size());
	}
	
	/**
	 * 获取文件集合
	 * @param dir 文件所在的文件夹
	 * @return
	 */
	private File[] getFileList(String dir) {
		File logFileDir = new File(dir);
		if(logFileDir.isDirectory()){
			File[] fileList = logFileDir.listFiles();
			return fileList;
		}
		return null;
	}
	
	/**
	 * 文件信息集合转换成日志信息集合
	 * @param dir 文件目录
	 * @return List<LogDTO>
	 */
	private List<LogDTO> getFileDTO(String dir){
		List<LogDTO> logDTOs = new ArrayList<LogDTO>();
		File[] fileLists = getFileList(dir);
		 Arrays.sort(fileLists); 
		if(fileLists!=null){
//			File temp = null;
//			for(int i = 0 ; i < fileLists.length -1 ; i ++){
//				for(int j = 0 ;j < fileLists.length - i - 1; j++){
//					//判断修改时间的大小，小的放在后面
//					if(fileLists[j].lastModified() > fileLists[j+1].lastModified() ){
//						temp = fileLists[j];
//						fileLists[j] = fileLists[j+1];
//						fileLists[j+1] = temp;
//					}
//				}
//			}
			int id = 1;
			for(File file : fileLists){
				LogDTO dto = new LogDTO();
				file2logDTO(file, dto,id++);
				logDTOs.add(dto);
			}
		}
		return logDTOs;
	}

	private void file2logDTO(File file,LogDTO dto,int id){
		dto.setId(id);
		dto.setFileName(file.getName());
		dto.setFileSize(String.format("%,dKB", (int)Math.ceil(file.length()/1024.0)));
		dto.setTime(TimeUtils.format(new Date(file.lastModified()),TimeUtils.DATETIME_PATTERN));
		dto.setUrl("");
	}
	/**
	 * 如果批量下载文件夹不存在就创建
	 * @param path
	 */
	private void fileMkdirs(String path){
		File file = new File(path);
		if (!file.exists()) {//如果文件夹不存在则创建
			file.mkdirs();
		}
	}
	
}
